package naga.x.platform2.support;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;

public class JSONIntArrayTypeHandler extends BaseTypeHandler<int[]> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, int[] parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, serialize(parameter));
	}

	@Override
	public int[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return deserialize(rs.getString(columnName));
	}

	@Override
	public int[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return deserialize(rs.getString(columnIndex));
	}

	@Override
	public int[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return deserialize(cs.getString(columnIndex));
	}
	
	private String serialize(int[] array) {
		return JSON.toJSONString(array);
	}
	
	private int[] deserialize(String json) {
		return JSON.parseObject(json, int[].class);
	}

}
